// main.js
import './style.css'
import { CodeEditor } from './editor.js'
import { 
    AutoCompletePlugin, 
    KeybindingPlugin, 
    SyntaxHighlightPlugin, 
    LSPClientPlugin,
    SearchReplacePlugin
} from './plugins/index.js'
import { createLogger } from './utils/logger.js'

const logger = createLogger('Main')

/**
 * 默认插件配置
 */
const defaultPluginConfig = {
    LSPClientPlugin: {
        enabled: true,
        options: {
            language: 'javascript',
            enableCompletion: true,
            enableDiagnostics: true,
            enableHover: true
        }
    },
    SyntaxHighlightPlugin: {
        enabled: true,
        options: {
            enableHighlighting: true,
            debounceDelay: 100,
            highlightLanguage: 'javascript'
        }
    },
    KeybindingPlugin: {
        enabled: true,
        options: {
            autoCloseBrackets: true,
            autoCloseQuotes: true,
            tabSize: 4
        }
    },
    AutoCompletePlugin: {
        enabled: true,
        options: {
            debounceDelay: 300,
            maxItems: 20
        }
    },
    SearchReplacePlugin: {
        enabled: true,
        options: {
            caseSensitive: false,
            wholeWord: false,
            useRegex: false,
            wrapSearch: true
        }
    }
}

/**
 * 创建并配置编辑器
 */
function createEditor(element, config = {}) {
    // 合并配置
    const finalConfig = {
        ...defaultPluginConfig,
        ...config
    }
    
    // 创建编辑器实例
    const editor = new CodeEditor(element, finalConfig)
    
    // 注册所有插件
    editor.registerPlugin('LSPClientPlugin', LSPClientPlugin)
    editor.registerPlugin('SyntaxHighlightPlugin', SyntaxHighlightPlugin)
    editor.registerPlugin('KeybindingPlugin', KeybindingPlugin)
    editor.registerPlugin('AutoCompletePlugin', AutoCompletePlugin)
    editor.registerPlugin('SearchReplacePlugin', SearchReplacePlugin)
    
    // 根据配置安装和启用插件
    editor.configurePlugins(finalConfig)
    
    // 监听插件事件（可选）
    setupEventListeners(editor)
    
    return editor
}

/**
 * 设置事件监听器
 */
function setupEventListeners(editor) {
    // 插件事件监听
    editor.on('plugin:enabled', (data) => {
        logger.plugin(`插件已启用: ${data.plugin}`)
    })
    
    editor.on('plugin:disabled', (data) => {
        logger.plugin(`插件已禁用: ${data.plugin}`)
    })
    
    // 语法高亮事件
    editor.on('syntaxHighlight:updated', () => {
        logger.debug('语法高亮已更新')
    })
    
    // 自动补全事件
    editor.on('autocomplete:show', (data) => {
        logger.debug(`显示自动补全: ${data.items.length} 项`)
    })
    
    // 键盘事件
    editor.on('keybinding:save', (data) => {
        logger.success(`文件已保存: ${data.filename}`)
    })
    
    // 搜索替换事件
    editor.on('searchReplace:replaced', (data) => {
        logger.success(`已替换 ${data.count} 处: "${data.searchText}" -> "${data.replaceText}"`)
    })
    
    editor.on('searchReplace:replacedAll', (data) => {
        logger.success(`全部替换完成，共 ${data.count} 处: "${data.searchText}" -> "${data.replaceText}"`)
    })
    
    // LSP事件
    editor.on('lsp:connected', (data) => {
        logger.info(`LSP客户端已连接: ${data.serverUrl || '本地模式'}`)
    })
}

/**
 * 页面加载完成后初始化编辑器
 */
document.addEventListener('DOMContentLoaded', () => {
    const app = document.querySelector('#app')
    if (app) {
        // 可以从 URL 参数或配置文件中读取自定义配置
        const customConfig = getCustomConfig()
        
        // 创建编辑器
        const editor = createEditor(app, customConfig)
        
        // 将编辑器实例暴露到全局，方便调试
        if (typeof window !== 'undefined') {
            window.editor = editor
            window.editorAPI = {
                enablePlugin: (name) => editor.enablePlugin(name),
                disablePlugin: (name) => editor.disablePlugin(name),
                getAllPlugins: () => editor.getAllPlugins(),
                getPlugin: (name) => editor.getPlugin(name)
            }
        }
        
        logger.success('编辑器初始化完成')
        logger.info('已安装的插件:', editor.getAllPlugins().map(p => p.name))
        logger.debug('使用 window.editorAPI 来控制插件')
    }
})

/**
 * 获取自定义配置
 * 可以从 URL 参数、localStorage 或配置文件中读取
 */
function getCustomConfig() {
    const config = {}
    
    // 从 URL 参数读取配置
    const urlParams = new URLSearchParams(window.location.search)
    
    // 例如: ?disableHighlight=true&disableAutoComplete=true
    if (urlParams.get('disableHighlight') === 'true') {
        config.SyntaxHighlightPlugin = { enabled: false }
    }
    
    if (urlParams.get('disableAutoComplete') === 'true') {
        config.AutoCompletePlugin = { enabled: false }
    }
    
    if (urlParams.get('disableKeybinding') === 'true') {
        config.KeybindingPlugin = { enabled: false }
    }
    
    if (urlParams.get('disableSearchReplace') === 'true') {
        config.SearchReplacePlugin = { enabled: false }
    }
    
    // 从 localStorage 读取配置
    try {
        const savedConfig = localStorage.getItem('editorConfig')
        if (savedConfig) {
            const parsedConfig = JSON.parse(savedConfig)
            Object.assign(config, parsedConfig)
        }
    } catch (error) {
        logger.warn('读取保存的配置失败:', error)
    }
    
    return config
}

// 导出创建函数，供其他模块使用
export { createEditor, defaultPluginConfig }